package file_create_tab

import (
	"fmt"
	"strconv"

	"file_explorer/common/consts"
	"file_explorer/view/packed_widgets"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

type FileCreateItem struct {
	*fyne.Container

	DeleteButton *packed_widgets.Button
	TypeSelect   *widget.Select
	NameEntry    *widget.Entry
	ScoreEntry   *widget.Entry
	ScoreEditBox *fyne.Container
	NoteEntry    *widget.Entry
	UrlEntry     *widget.Entry
	TagEntry     *widget.Entry
}

func newFileCreateItem() *FileCreateItem {
	item := &FileCreateItem{}

	item.DeleteButton = packed_widgets.NewButton("", theme.DeleteIcon(), nil)

	item.TypeSelect = widget.NewSelect([]string{consts.FileTypeStrRegular, consts.FileTypeStrDir}, nil)
	item.TypeSelect.Selected = consts.FileTypeStrRegular

	item.NameEntry = widget.NewEntry()
	item.NameEntry.PlaceHolder = "名称"

	item.ScoreEntry = widget.NewEntry()
	item.ScoreEntry.PlaceHolder = "评分"
	item.ScoreEntry.Validator = func(score string) error {
		if len(score) == 0 {
			return nil
		}
		_, err := strconv.Atoi(item.ScoreEntry.Text)
		if err != nil {
			return fmt.Errorf("input score is not number")
		}
		return nil
	}
	item.ScoreEditBox = container.NewBorder(
		nil, nil,
		widget.NewButton("-", func() {
			scoreInt, err := strconv.Atoi(item.ScoreEntry.Text)
			if err != nil {
				scoreInt = 0
			}
			item.ScoreEntry.SetText(strconv.Itoa(scoreInt - 1))
		}),
		widget.NewButton("+", func() {
			scoreInt, err := strconv.Atoi(item.ScoreEntry.Text)
			if err != nil {
				scoreInt = 0
			}
			item.ScoreEntry.SetText(strconv.Itoa(scoreInt + 1))
		}),
		item.ScoreEntry,
	)

	item.NoteEntry = widget.NewEntry()
	item.NoteEntry.MultiLine = true
	item.NoteEntry.PlaceHolder = "备注"

	item.UrlEntry = widget.NewEntry()
	item.UrlEntry.PlaceHolder = "链接"

	item.TagEntry = widget.NewEntry()
	item.TagEntry.PlaceHolder = "标签 (逗号隔开)"

	item.Container = container.NewBorder(
		nil, nil, item.DeleteButton, nil,
		container.NewGridWithColumns(2,
			container.NewGridWithRows(3,
				container.NewGridWithColumns(2, item.TypeSelect, item.NameEntry),
				container.NewGridWithColumns(2, item.ScoreEditBox, item.TagEntry),
				item.UrlEntry,
			),
			item.NoteEntry,
		),
	)

	return item
}
